﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Web;
using System.Web.Routing;
using ChgDoc.Entity;
using ChgDoc.Render;
using System.Web.SessionState;
using StackExchange.Profiling;

namespace ChgDoc
{
    public class ResponseHandler : IHttpHandler, IRequiresSessionState 
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            MiniProfiler.Start();

            Config.Log.Info("URL Request: " + context.Request.Url);

			// Get URL or Homepage name
        	var url = context.Request.RequestContext.RouteData.Values[ "url" ] as string;
			if (String.IsNullOrEmpty( url ))
				url = PageResponseSpecialNames.Homepage;

            PageResponse pageResp = PageResponse.Read(url);
			if (pageResp == null)
		        pageResp = PageResponse.Read( PageResponseSpecialNames.FourOhFour );			

            if (pageResp == null)
            {
                string urlBase = context.Request.Url.ToString().Substring(0, context.Request.Url.ToString().Length - context.Request.Url.PathAndQuery.Length) + (context.Request.ApplicationPath == "/" ? "/" : context.Request.ApplicationPath + "/");
                context.Response.Write("<html>It's so bad... I couldn't even give you a 404 page. Try going to <a href=\"" + urlBase + "edit/setuptasks.aspx\">Setup Tasks</a>");
            }
			else
        	{
                PageHitCount.Track(context.Request.RawUrl, pageResp);

                var renderer = ResponseRender.Create(pageResp);
                if (renderer != null)
                {
                    renderer.Render(context);
                }
            }

            MiniProfiler.Stop();
        }

    }

    public class HttpHandlerRouteHandler<THandler> : IRouteHandler where THandler : IHttpHandler, new()
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new THandler();
        }
    }
}